package com.xhwl.centiotdata.suppliersystem.haikang;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.constant.HaiKangConstant;
import com.xhwl.centiotdata.pojo.dto.haikang.RegionHaiKangDTO;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.common.pojo.cent.iot.OrgInfo;
import com.xhwl.common.utils.StringUtils;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author： lianghz
 * @Description：
 * @Date 2021/11/17/ 14:05
 */
@Service
public class RegionHaiKangHandler {
    private static final Logger log = LoggerFactory.getLogger(RegionHaiKangHandler.class);

    @Autowired
    private GeneralHaiKangHandler generalHaiKangHandler;

    public List<RegionHaiKangDTO> detailRegion(List<String> indexCodes, Integer projectId, Integer productId, String ipAndPort, String ak, String sk, String tagId) {
        Map<String, Object> params = new HashMap<>(1);
        params.put("indexCodes", indexCodes);
        JSONObject dataObject = generalHaiKangHandler.post(HaiKangConstant.REGION_INFO_URL, params, projectId, productId, ipAndPort, ak, sk, tagId);
        JSONArray list = dataObject.getJSONArray("list");
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.toJavaList(RegionHaiKangDTO.class);
    }


    /**
     * 批量创建组织
     *
     * @param config   配置
     * @param infoList 组织列表
     * @return 组织列表
     */
    public List<OrgInfo> createOrg(PedestrianIntegrationConfigDTO config, List<OrgInfo> infoList) {
        try {
            infoList.forEach(info -> {
                JSONObject jsonData = generalHaiKangHandler.post(HaiKangConstant.ORG_ADD_URL, Collections.singletonList(info),
                        config.getProjectId(), config.getProductId(),
                        config.getIpAndPort(), config.getAk(), config.getSk(), config.getTagId());
                //新增成功数据
                JSONArray successes = jsonData.getJSONArray("successes");
                List<OrgCreateResults> orgCreateResults = successes.toJavaList(OrgCreateResults.class);
                if (orgCreateResults.size() > 0) {
                    info.setOrgIndexCode(orgCreateResults.get(0).getOrgIndexCode());
                }
                //新增失败数据
                JSONArray failures = jsonData.getJSONArray("failures");
                if (!CollectionUtils.isEmpty(failures)) {
                    log.error("同步组织失败:{}", failures);
                }
            });
        } catch (Exception e) {
            log.error("新增组织异常", e);
        }
        return infoList;
    }

    /**
     * 修改组织信息
     *
     * @param config  配置
     * @param orgInfo 组织信息
     * @return 更新结果
     */
    public boolean updateOrg(PedestrianIntegrationConfigDTO config, OrgInfo orgInfo) {
        try {
            JSONObject jsonData = generalHaiKangHandler.post(HaiKangConstant.ORG_UPDATE_URL, orgInfo,
                    config.getProjectId(), config.getProductId(),
                    config.getIpAndPort(), config.getAk(), config.getSk(), config.getTagId());
            if (!Objects.equals("0", jsonData.getString("code"))) {
                log.error("修改组织失败:{}", jsonData.getString("msg"));
                return false;
            }
        } catch (Exception e) {
            log.error("修改组织异常", e);
            return false;
        }
        return true;
    }

    /**
     * 批量删除组织
     *
     * @param config   配置
     * @param infoList 组织列表
     */
    public void deleteOrg(PedestrianIntegrationConfigDTO config, List<OrgInfo> infoList) {
        try {
            JSONObject param = new JSONObject();
            List<String> indexCodes = infoList.stream().map(OrgInfo::getOrgIndexCode).collect(Collectors.toList());
            param.put("indexCodes", indexCodes);
            JSONObject jsonData = generalHaiKangHandler.post(HaiKangConstant.ORG_DELETE_URL, param,
                    config.getProjectId(), config.getProductId(),
                    config.getIpAndPort(), config.getAk(), config.getSk(), config.getTagId());
            log.info("组织删除结果:{}", jsonData);
        } catch (Exception e) {
            log.error("删除组织异常", e);
        }
    }

    @Data
    private static class OrgCreateResults {
        private Integer clientId;
        private String orgIndexCode;
    }

}
